package com.ecoolex.discount.sales.core.manager;

import com.ecoolex.discount.sales.core.dao.DiscountOrderRefundDAO;
import com.ecoolex.discount.sales.entity.DiscountOrderRefund;
import com.ecoolex.discount.sales.entity.DiscountOrderRefund.Column;
import com.ecoolex.discount.sales.entity.DiscountOrderRefundExample;
import com.ecoolex.discount.sales.entity.DiscountOrderRefundExample.Criteria;
import com.ecoolex.framework.common.util.Check;

import java.time.Instant;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DiscountOrderRefundManager {
	
    @Autowired
    private DiscountOrderRefundDAO dao;
    
    public void create(DiscountOrderRefund record,String createUser) {
    	record.setDeleted(DiscountOrderRefund.NOT_DELETED);
    	record.setCreateUser(createUser);
    	record.setCreateTime(Date.from(Instant.now()));
    	record.setUpdateUser(createUser);
    	record.setUpdateTime(Date.from(Instant.now()));
    	dao.insert(record);
    }
    
    public void updateToCancel(Integer orderId,String updateUser) {
    	DiscountOrderRefund record = getByOrderId(orderId);
    	if(Check.notNull(record)) {
    		record.setRefundStatus("customer_canceled");
    		record.setUpdateTime(Date.from(Instant.now()));
    		record.setUpdateUser(updateUser);
    		dao.updateByPrimaryKey(record);
    	}
    }
    
    public void update(DiscountOrderRefund record,String updateUser) {
    	record.setUpdateUser(updateUser);
    	record.setUpdateTime(Date.from(Instant.now()));
    	dao.updateByPrimaryKey(record);
    }
    
    public DiscountOrderRefund getByOrderId(Integer orderId) {
    	DiscountOrderRefundExample example = new DiscountOrderRefundExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andOrderIdEqualTo(orderId).andDeletedEqualTo(DiscountOrderRefund.NOT_DELETED);
    	example.orderBy(Column.applyTime.desc());
    	example.limit(1);
    	return dao.selectOneByExample(example);
    }
}